import React, { PureComponent, Fragment } from 'react';

import {
  Input,
  Tabs,
  Row,
  Typography,
  Col,
  Checkbox,
  Radio,
  Button,
  Icon,
  Select,
  Form,
  TreeSelect,
} from 'antd';

import { connect } from 'dva';
import router from 'umi/router';
import _ from 'lodash';
import * as utils from '../utils/treeUtils';
import styles from './index.less';

const { Text } = Typography;

const FormItem = Form.Item;

const { Option } = Select;

@connect(state => ({
  searched: state.ContractPlanEntireProjectItems.searched,
  searchItems: state.ContractPlanEntireProjectItems.searchItems,
  all: state.ContractPlanEntireProjectItems.all,
  overAllYears: state.ContractPlanEntireProjectItems.overAllYears,
  currentYear: state.ContractPlanEntireProjectItems.currentYear,
  currentMonths: state.ContractPlanEntireProjectItems.currentMonths,
  currentShowGroup: state.ContractPlanEntireProjectItems.currentShowGroup,
}))
@Form.create()
export default class PageTop extends PureComponent {
  state = {
    expandForm: false,
    productType: '',
  };

  // 根据查询条件搜索
  handleSearch = e => {
    const self = this;
    e.preventDefault();
    const { dispatch, form, currentYear, match } = this.props;
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      const values = _.values(
        _.mapValues(fieldsValue, value =>
          value ? value.split('|')[1].replace(/\(.*\)/, '') : 'null',
        ),
      ).join('/');
      this.props.getItems(this.props, values);
    });
  };

  // 重置查询条件
  handleFormReset = () => {
    const { form } = this.props;
    form.resetFields();
    this.setState({
      productType: '',
    });
    // this.props.getItems(this.props, currentYear, match.params.project);
  };

  // 切换搜索条件的展示方式
  toggleForm = () => {
    const self = this;
    this.setState({
      expandForm: !self.state.expandForm,
    });
    this.props.expandForm(!self.state.expandForm);
  };

  // 搜索条件的展示方式———展开
  renderAdvancedForm = () => {
    const formItemLayout = {
      labelCol: { span: 8 },
      wrapperCol: { span: 16 },
      style: { marginBottom: 0 },
    };
    const { getFieldDecorator, setFieldsValue } = this.props.form;
    const { searchItems } = this.props;
    const { productType } = this.state;

    // 组团
    let products = [];
    let productTypes = [];
    // 业态
    products = utils.getSearchTypeItems(searchItems.org_product, 'name', 'id');
    // 产品构成
    productTypes = utils.getSearchTypeItems(
      searchItems.org_product,
      'proProductName',
      'proProductCode',
    );

    if (productType) {
      const orgProduct = searchItems.org_product;
      let orgStage = [];
      orgStage = _.filter(orgProduct, { proProductCode: productType });
      products = utils.getSearchSeltetItems(orgStage, 'org_product', 'name', 'id');
    }

    return (
      <Form onSubmit={this.handleSearch} layout="inline">
        <Row type="flex" justify="center" align="middle">
          <Col md={20} sm={24}>
            <FormItem label="业态">
              {getFieldDecorator('productType', {
                // initialValue: '',
              })(
                <Select
                  dropdownMatchSelectWidth={false}
                  size="small"
                  style={{ minWidth: 100 }}
                  onChange={value => {
                    setFieldsValue({ product: '' });
                    this.setState({
                      productType: value.split('|')[0],
                    });
                  }}
                  placeholder="全部"
                >
                  <Option value="">全部</Option>
                  {productTypes &&
                    productTypes.length > 0 &&
                    productTypes.map(value => (
                      <Option key={value.code} value={`${value.code}|${value.name}`}>
                        {value.name || '暂无名称'}
                      </Option>
                    ))}
                </Select>,
              )}
            </FormItem>
            <FormItem label="产品构成">
              {getFieldDecorator('product', {
                // initialValue: '',
              })(
                <Select
                  dropdownMatchSelectWidth={false}
                  style={{ minWidth: 150 }}
                  size="small"
                  placeholder="全部"
                >
                  <Option value="">全部</Option>
                  {products &&
                    products.length > 0 &&
                    products.map(value => (
                      <Option key={value.code} value={`${value.code}|${value.name}`}>
                        {value.name || '暂无名称'}
                      </Option>
                    ))}
                </Select>,
              )}
            </FormItem>
          </Col>
          <Col md={3} sm={24} justify="space-around" align="middle">
            <Button type="primary" htmlType="submit">
              查询
            </Button>
            <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>
              重置
            </Button>
          </Col>
        </Row>
      </Form>
    );
  };

  changeCurrentMonths = value => {
    const { dispatch } = this.props;
    dispatch({
      type: 'ContractPlanEntireProjectItems/changeCurrentMonths',
      payload: {
        currentMonths: value,
      },
    });
  };

  changeCurrentShowGroup = value => {
    const { dispatch } = this.props;
    dispatch({
      type: 'ContractPlanEntireProjectItems/changeCurrentShowGroup',
      payload: {
        currentShowGroup: value,
      },
    });
  };
  changeCurrentYear(value) {
    const { dispatch } = this.props;
    const self = this;
    dispatch({
      type: 'ContractPlanEntireProjectItems/changeCurrentYear',
      payload: {
        currentYear: value,
      },
      callback: () => {
        self.props.getItems(self.props);
      },
    });
  }

  render() {
    const months = [
      {
        title: '年度合计',
        value: '14',
        key: '14',
      },
      {
        title: '全部月份',
        value: '13',
        key: '13',
        children: [
          { key: '1', value: '1', title: '1月' },
          { key: '2', value: '2', title: '2月' },
          { key: '3', value: '3', title: '3月' },
          { key: '4', value: '4', title: '4月' },
          { key: '5', value: '5', title: '5月' },
          { key: '6', value: '6', title: '6月' },
          { key: '7', value: '7', title: '7月' },
          { key: '8', value: '8', title: '8月' },
          { key: '9', value: '9', title: '9月' },
          { key: '10', value: '10', title: '10月' },
          { key: '11', value: '11', title: '11月' },
          { key: '12', value: '12', title: '12月' },
        ],
      },
    ];
    const {
      overAllYears,
      currentYear,
      currentMonths,
      searched,
      versionOptions,
      currentShowGroup,
    } = this.props;
    return (
      <Fragment>
        <div className={styles.entireProjectHeader}>
          <div className="header-categories">
            <div className={styles.entireProjectHeader}>
              <Row align="middle" type="flex" style={{ height: '100%', width: '100%' }}>
                <Col>
                  <span style={{ paddingRight: '10px' }}>显示:</span>
                  <Checkbox.Group
                    defaultValue={['dynamic']}
                    disabled
                    options={[{ label: '全盘动态', value: 'dynamic' }]}
                  />
                  <Radio.Group defaultValue="getprice">
                    {versionOptions &&
                      versionOptions.map(data => (
                        <Radio value={data.value} key={data.value}>
                          {data.label}
                        </Radio>
                      ))}
                  </Radio.Group>
                  {/* <Checkbox.Group
                    onChange={this.props.onChangeAttributesCheckeds}
                    options={attributes}
                    defaultValue={attributesCheckeds}
                  /> */}
                </Col>
                <Col>
                  <Select
                    // mode="multiple"
                    size="small"
                    style={{ width: 140 }}
                    placeholder="请选择"
                    value={!currentShowGroup ? '期初存货/新供/综合' : currentShowGroup + ''}
                    onChange={e => this.changeCurrentShowGroup(e)}
                  >
                    <Option key="期初存货/新供/综合">期初存货/新供/综合</Option>
                    <Option key="期初存货">期初存货</Option>
                    <Option key="新供">新供</Option>
                    <Option key="综合">综合</Option>
                  </Select>
                  &nbsp;&nbsp;
                  {currentYear !== '' ? (
                    <>
                      <Select
                        // mode="multiple"
                        size="small"
                        style={{ width: 100 }}
                        placeholder="请选择"
                        value={currentYear}
                        onChange={e => this.changeCurrentYear(e)}
                      >
                        {overAllYears &&
                          overAllYears.length > 0 &&
                          overAllYears.map(data => (
                            <Option key={data}>
                              {data}
                              {new Date().getFullYear().toString() === data.toString()
                                ? '(今年)'
                                : ''}
                            </Option>
                          ))}
                      </Select>
                      &nbsp;&nbsp;
                      <TreeSelect
                        size="small"
                        style={{ width: 230 }}
                        value={currentMonths}
                        mode="multiple"
                        onChange={this.changeCurrentMonths}
                        treeCheckable
                        maxTagCount={2}
                        treeData={months}
                      ></TreeSelect>
                    </>
                  ) : null}
                </Col>
              </Row>
            </div>
          </div>

          <div>
            {searched && searched.length ? (
              <Button onClick={this.toggleForm}>
                高级筛选
                {<Icon type={this.state.expandForm ? 'up' : 'down'} />}
              </Button>
            ) : null}
          </div>
        </div>
        <div className="header-search-area">
          {this.state.expandForm ? this.renderAdvancedForm() : null}
        </div>
      </Fragment>
    );
  }
}
